package cn.fx.framework.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.support.WebApplicationContextUtils;
import jakarta.validation.Validator;
import jakarta.servlet.http.HttpServletRequest;

/**
 * Created by ljh on 2017/7/8.
 */
public class SpringBeans implements ApplicationContextAware {
    private static ApplicationContext wac = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext){
        wac = applicationContext;
    }

    public SpringBeans() {
    }

    public static Object getBean(String name) {
        Object bean = wac.getBean(name);
        if(bean == null) {
            throw new RuntimeException("spring窗口中没有找到名字为‘" + name + "’的bean.");
        } else {
            return bean;
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        T t = wac.getBean(clazz);
        if(t == null) {
            throw new RuntimeException("spring窗口中没有找到名字为‘" + clazz.getName() + "’的bean.");
        } else {
            return t;
        }
    }

    /**
     * 从Http请求中获取spring托管的bean对象
     * @param clazz
     * @param request
     * @param <T>
     * @return
     */
    public static <T> T getBeanFromRequest(Class<T> clazz, HttpServletRequest request){
        ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());

        //ConfigurableApplicationContext context = (ConfigurableApplicationContext) ac;
        //Bean的实例工厂
        //DefaultListableBeanFactory dbf = (DefaultListableBeanFactory) context.getBeanFactory();
        return ac.getBean(clazz);
    }

    private static Validator validator = null;

    public static Validator getBeanValidator(HttpServletRequest request){
        if(validator == null){
            ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            validator = ac.getBean(Validator.class);
        }
        return validator;
    }
}
